/*
 * @Author: lihaogn
 * @Date: 2022-01-23 21:18:37
 * @LastEditTime: 2022-01-23 23:09:07
 * @LastEditor: lihaogn
 * @Description:
 * @FilePath: \lix-admin-server\app\service\upload.js
 */
const Service = require("egg").Service;
const fs = require("fs");
const commonUtils = require("../utils/commonUtils");

class UploadService extends Service {
  /**
   * @author: lihaogn
   * @Date: 2022-01-26 15:31:32
   * @description: 下载文件
   * @param {*} id - 文件 id
   * @return {*}
   */
  async download(id) {
    const { app } = this;
    try {
      // 根据 id 找到要下载的文件信息
      const download = await app.model.Upload.findByPk(id);

      return download;
    } catch (error) {
      console.log("download err", error);
      return false;
    }
  }

  /**
   * @author: lihaogn
   * @Date: 2022-01-24 20:59:33
   * @description: 删除上传文件记录
   * @param {*} id
   * @return {*}
   */
  async deleteUpload(id) {
    const { app } = this;
    try {
      // 根据 id 去查询要删除的文件
      // 获取到地址，然后去删除
      const upload = await app.model.Upload.findByPk(id);
      if (upload) {
        fs.unlinkSync(upload.path);

        const res = await app.model.Upload.destroy({
          where: { id },
        });

        return res;
      }
    } catch (err) {
      console.log("deleteUpload err", err);
      return false;
    }
  }
  /**
   * @author: lihaogn
   * @Date: 2022-01-23 22:40:57
   * @description: 查询上传文件列表
   * @param {*}
   * @return {*}
   */
  async queryUploads() {
    const { app } = this;
    try {
      const res = await app.model.Upload.findAll();
      return res;
    } catch (err) {
      console.log(err);
      return false;
    }
  }
  /**
   * @author: lihaogn
   * @Date: 2022-01-23 21:39:54
   * @description: 上传的文件信息入库
   * @param {*} path - 文件地址
   * @param {*} name - 文件名称
   * @return {*}
   */
  async createUpload(path, name, url) {
    const { app } = this;
    try {
      const upload = await app.model.Upload.create({
        id: commonUtils.getUUID(),
        name,
        path,
        url,
      });
      return upload;
    } catch (err) {
      console.log(err);
      return false;
    }
  }
}

module.exports = UploadService;
